package main

import (
	"flag"
	"micro-rulego/internal/broker"
	"micro-rulego/internal/conf"
	nats "micro-rulego/pkg/nats/broker"
	"os"

	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/config"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/registry"
	"github.com/go-kratos/kratos/v2/transport/grpc"

	_ "go.uber.org/automaxprocs"
)

// go build -ldflags "-X main.Version=x.y.z"
var (
	// Name is the name of the compiled software.
	Name = "micro-rulego.wireless.template.service"
	// Version is the version of the compiled software.
	Version string
	// flagconf is the config flag.
	flagconf string

	id, _ = os.Hostname()
)

func init() {
	flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml")
}

func newApp(logger log.Logger, gs *grpc.Server, rr registry.Registrar) *kratos.App {
	return kratos.New(
		kratos.ID(id),
		kratos.Name(Name),
		kratos.Version(Version),
		kratos.Metadata(map[string]string{}),
		kratos.Logger(logger),
		kratos.Server(
			gs,
		),
		kratos.Registrar(rr),
	)
}

func newBroker(logger log.Logger) (broker.Broker, func(), error) {
	blogger := log.NewHelper(logger)
	b := nats.NewBroker(
		broker.ErrorHandler(func(e broker.Event) error {
			blogger.Error(e.Error())
			return nil
		}),
		broker.BrokerName(Name+"."+id),
	)
	err := b.Connect()
	if err != nil {
		return nil, nil, err
	}
	cleanup := func() {
		b.Disconnect()
	}
	return b, cleanup, nil
}

func loadConfig(cs config.Source) (*conf.Bootstrap, func()) {
	c := config.New(
		config.WithSource(
			cs,
		),
	)
	if err := c.Load(); err != nil {
		panic(err)
	}
	var bc conf.Bootstrap
	if err := c.Scan(&bc); err != nil {
		panic(err)
	}
	return &bc, func() {
		c.Close()
	}
}

func main() {
	flag.Parse()
	cs, err := newFileSource(flagconf)
	if err != nil {
		panic(err)
	}
	rr, err := newConsulRegistrar()
	if err != nil {
		panic(err)
	}
	AppWrapper, cleanup, err := initApp(cs, rr)
	if err != nil {
		panic(err)
	}
	defer cleanup()
	err = AppWrapper.Debug.Start()
	if err != nil {
		log.Fatalf("启动telnet服务器失败: %v", err)
	}
	defer AppWrapper.Debug.Stop()
	// start and wait for stop signal
	if err := AppWrapper.App.Run(); err != nil {
		panic(err)
	}
}
